package designPattern;

import java.util.Arrays;

public class DCL {

    // 禁止指令重排
    private static volatile DCL dcl;

    private DCL() {
    }

    // 双端检锁 Double Check Lock
    public static DCL getDcl() {
        if (dcl == null) { // 如果先设置引用，这里就会出现问题，会返回未初始化好的对象
            synchronized (DCL.class) {
                if (dcl == null) {
                    // 分配内存、初始化、设置引用
                    dcl = new DCL();
                }
            }
        }
        return dcl;
    }

    public static void main(String[] args) {
        Thread[] ths = new Thread[200];
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new Thread(() -> {
                System.out.println(DCL.getDcl());
            });
        }

        Arrays.asList(ths).forEach(Thread::start);
    }
}
